import Taro, { Component, Config } from '@tarojs/taro'
import { Image, ScrollView, Text, View } from '@tarojs/components'
import classNames from 'classnames'
// import lodash from "@/utils/lodash"
import { pxTransform } from "@/utils/utils"
import moment from "@/assets/js/moment.min"
import ServiceIcon from "@/assets/images/service-icon.png"
import { SHARE_ID } from "@/config/storage"
import { SHARE_TYPE } from "@/config/types"
import { getPage } from "@/api/productApi"
import { getCustomPage } from "@/api/pageApi"
import { shareInfoById } from "@/api/wximagesApi"
import { toAnyPage, toGoodsPage, toSearchPage, toServiceComplaint, toService, toOrderListPage } from "@/utils/page_router"
import { getSharePath, getActivityTimeStorage, setActivityTimeStorage } from '@/utils/storage'
import { APP_NAME, TAB_BAR_HEIGHT, NAV_BAR_HEIGHT } from '@/config/config'
import { TabBar, Loading, Version, LoadMore, BuyRecord, FyImg } from '@/components/index'
import ActivityGoods from "@/components/activity/goods/index"
import TabList from '../tab-list/index'
// import ActivityCoupon from "@/components/activity/coupon/index"
import NewsOne from "@/components/custom-layout/news-one"
import NavGroupTwo from "@/components/custom-layout/nav-group-two"
import CarouselTwo from "@/components/custom-layout/carousel-two"
import GoodsOne from "@/components/custom-layout/goods-one"
import GoodsTwo from "@/components/custom-layout/goods-two"
import GoodsThree from "@/components/custom-layout/goods-three"
import GoodsFour from "@/components/custom-layout/goods-four"
import GoodsFive from "@/components/custom-layout/goods-five"
import GoodsSix from "@/components/custom-layout/goods-six"
import GoodsSeven from "@/components/custom-layout/goods-seven"
import GoodsEight from "@/components/custom-layout/goods-eight"
import GoodsNine from "@/components/custom-layout/goods-nine"
import GoodsTen from "@/components/custom-layout/goods-ten"
import GridImg from "@/components/custom-layout/grid-img"
import BlankSpace from "@/components/custom-layout/blank-space"
import AuxiliaryLine from "@/components/custom-layout/auxiliary-line"
import GoodsCategories from "@/components/custom-layout/goods-categories"
import ActivityTheme from "@/components/custom-layout/activity-theme"
import Promotion from "@/components/custom-layout/promotion"
import ScrollTop from "@/components/scroll-top"
// import './index.scss'
import styles from './index.module.scss'

const defTabKey = 'recommend'
let CAROUSEL_HEIGHT = 0
const TAB_NAV_HEIGHT = 72

const scroll: any = {}
// const { capsule } = APP_SYSTEM_INFO
export default class Index extends Component {
  state: any
  navId: string
  tabId: string
  navBar: any
  tabNav: any
  pageConfig: any
  activityInfo: any
  config: Config = {
    navigationStyle: 'custom',
    backgroundTextStyle: "dark",
    enablePullDownRefresh: true,
  }

  constructor() {
    super(...arguments)
    this.state = {
      tabKey: defTabKey,
      loading: true,
      customList: [],
      page: 1,
      limit: 10,
      goodsList: [],
      loadStatus: 'loading',
      showActivity: false,
      zhiding: false,
      duihuanbi: true,
    }
    this.navId = `nav-${Number(new Date())}`
    this.tabId = `tab-${Number(new Date())}`
    this.pageConfig = {}
  }

  componentDidMount() {
    this.getShareInfo()
    this.getIndexData()
  }

  //  下拉刷新
  onPullDownRefresh() {
    const { tabKey } = this.state
    if (tabKey === defTabKey) {
      this.getIndexData()
    } else {
      this.setState({
        page: 1,
        goodsList: [],
        loadStatus: 'loading'
      }, () => {
        this.getGoods()
      })
    }
  }

  onPageScroll(res: any) {
    scroll.onPageScroll && scroll.onPageScroll(res.scrollTop)
    scroll.onPageScrolal && scroll.onPageScrolal(res.scrollTop)
    if (res.scrollTop > 300) {
      this.setState({
        zhiding: true,
      })
    } else {
      this.setState({
        zhiding: false,
      })
    }
    if (res.scrollTop) {
      this.setState({
        duihuanbi: false,
      })
    } else {
      this.setState({
        duihuanbi: true,
      })
    }
  }

  //  上拉加载
  onReachBottom() {
    this.getGoods()
    scroll.onReachBottom && scroll.onReachBottom()
  }

  //  分享小程序
  onShareAppMessage() {
    return { title: APP_NAME, path: getSharePath() }
  }

  //  获取分享信息
  getShareInfo() {
    const { params: { scene } }: any = this.$router
    if (scene) {
      Taro.setStorageSync(SHARE_ID, scene)
      shareInfoById(scene).then(({ data }) => {
        const arr = [
          SHARE_TYPE.GOODS_INFO,
          SHARE_TYPE.NORMAL_GOODS,
          SHARE_TYPE.SCORE_GOODS,
          SHARE_TYPE.SECKILL_GOODS,
          SHARE_TYPE.PINK_GOODS,
          SHARE_TYPE.REAL_GOODS,
          SHARE_TYPE.VIRTUAL_GOODS,
        ]
        if (arr.indexOf(data.keyType) >= 0) {
          toGoodsPage({ id: data.keyId, type: data.keyType, saleStrategy: data.keyType }, true)
        }
      })
    }
  }

  //  获取首页数据
  getIndexData() {
    const { params } = this.$router
    getCustomPage(params.key).then(({ data, timestamp }) => {
      const list = (data.content || []).map(item => {
        switch (item.key) {
          case 'navGroup':
            const { list = [], colNumber = 5, rowNumber = 2 } = item
            //  乘积
            const product = colNumber * rowNumber
            const num = Math.ceil(list.length / product)
            const arr: any = []
            for (let i = 0; i < num; i++) {
              arr.push([])
            }
            for (let i = 0; i < list.length; i++) {
              arr[Math.floor(i / product)].push(list[i])
            }

            item.list = arr
            break
          case 'carousel':
            CAROUSEL_HEIGHT = item.height
            break
          case 'navBar':
            this.navBar = item
            break
          case 'tabNav':
            this.tabNav = item
            break
          case 'pageConfig':
            this.pageConfig = item
            break
          case 'activityGoods':
            this.activityInfo = item
            break
        }
        return item
      })
      this.setState({
        customList: list
      }, () => {
        this.setState({
          loading: false
        })
        Taro.stopPullDownRefresh()
      })

      this.activityInfo && setTimeout(() => {
        this.showActivity(timestamp, this.activityInfo)
      }, 3000)
    })
  }

  //  显示活动
  showActivity(time: number, goods: any) {
    const item = getActivityTimeStorage(goods.id)
    if (!item || item && moment(time).isAfter(item['time'])) {
      setActivityTimeStorage(goods.id, {
        id: goods.id,
        type: 'goods',
        time: time + 86400000
      })
      this.setState({
        showActivity: true,
      })
    }
  }

  //  关闭活动
  closeActivity() {
    this.setState({
      showActivity: false,
    })
  }

  //  分页获取商品
  getGoods() {
    const { page, limit, tabKey, goodsList, loadStatus }: any = this.state
    const query = {}
    //今日优选
    if (tabKey === 'recommend') {
      query['type'] = 1
    } else if (tabKey === '3') {
      //其它分类
      query['type'] = 2
    }

    if (loadStatus === 'noMore') {
      return
    }

    if (tabKey !== defTabKey) {
      query['categoryId'] = tabKey
    }
    getPage({ page, limit, ...query }).then(res => {
      const { list, totalCount } = res.data
      this.setState({
        page: page + 1,
        goodsList: page === 1 ? list : goodsList.concat(list),
        loadStatus: (page * limit >= totalCount) ? 'noMore' : 'loading',
      }, () => {
        Taro.stopPullDownRefresh()
      })
    })
  }

  //  切换tab
  onSwitchTab(key) {
    console.log(key)
    this.setState({
      tabKey: key,
      page: 1,
      goodsList: [],
      loadStatus: 'loading'
    }, () => {
      this.getGoods()
    })
  }

  showDuihuanbi() {
    this.setState({
      duihuanbi: true
    })
  }


  render() {
    const { navBar, tabNav, pageConfig, activityInfo } = this
    const { customList, tabKey, loading, goodsList, loadStatus, showActivity, zhiding, duihuanbi } = this.state
    {/*// @ts-ignore*/ }
    return (<View className={`${styles.index}`}>
      <ScrollTop ref="ScrollTop" zhiding={zhiding} duihuanbi={duihuanbi} showDuihuanbi={this.showDuihuanbi.bind(this)} />
      {/*<View className='custom-page-bgImg' style={{ backgroundImage: `url(${pageConfig.bgImg})` }}></View>*/}
      {loading && <Loading isCover />}
      {/* 顶部导航栏 */}
      {/*{pageConfig.showNavBar && navBar && <View style={{ height: pxTransform(NAV_BAR_HEIGHT) }}/>}*/}
      {/*{pageConfig.showNavBar && navBar && <View style={{ height: pxTransform(NAV_BAR_HEIGHT) }}/>}*/}
      {pageConfig.showNavBar && navBar && <View
        id={this.navId}
        className={`fy-popup fy-popup--top ${styles.navBar}`}
        style={{ height: pxTransform(NAV_BAR_HEIGHT), backgroundImage: `url(${pageConfig.bgImg})`, backgroundPosition: `left 50% bottom -${pxTransform(CAROUSEL_HEIGHT + TAB_NAV_HEIGHT)}` }}>
        <View className={`${styles.navBarArea} d-f a-i-c`}>
          {navBar.img && <Image src={navBar.img} className={`${styles.navBarLogo}`} />}
          <View className={`${styles.navBarInput} d-f a-i-c`} onClick={() => toSearchPage()}>
            <View className='bnn-icon m-r-10'>&#xe65c;</View>
            <View>{navBar.placeholder}</View>
          </View>
          <View className={classNames(styles.ServiceIcon, 'd-f', 'f-d-c', 'f-g-5')} onClick={() => { toServiceComplaint() }}>
            <FyImg src={ServiceIcon} className={styles.icon} />
            <Text className={styles.text}>客服</Text>
          </View>
        </View>
      </View>}
      {/* 顶部选项卡导航 */}
      {/*{pageConfig.showTabNav && tabNav && <View className={`${styles.tabNavHeight}`}/>}*/}
      {/*{pageConfig.showTabNav && tabNav && <View className={`${styles.tabNavHeight}`}/>}*/}
      {pageConfig.showTabNav && tabNav && <View className={styles.tabHeight}></View>}
      {pageConfig.showNavBar && <View style={{ height: pxTransform(NAV_BAR_HEIGHT) }} />}
      {pageConfig.showTabNav && tabNav && <View id={this.tabId} className={styles.tabNav} style={{
        top: pageConfig.showNavBar ? pxTransform(NAV_BAR_HEIGHT) : '0px',
        color: tabNav.color,
        backgroundPosition: `left 50% bottom -${pxTransform(CAROUSEL_HEIGHT)}`,
        backgroundImage: `url(${pageConfig.bgImg})`
      }}>
        <TabList
          info={tabNav}
          current={defTabKey}
          onClick={this.onSwitchTab.bind(this)}
        />
        {/*<View className={classNames(`${styles.tabNavLeft} ${styles.tabNavCtyItem}`, {[`${styles.tabNavCtyActive}`]: tabKey === defTabKey})} onClick={this.onSwitchTab.bind(this, defTabKey)}>*/}
        {/*  <Text className={`${styles.tabNavCtyText}`}>精选</Text>*/}
        {/*</View>*/}
        {/*// @ts-ignore*/}
        {/*<ScrollView scrollX enhanced showScrollbar={false} className={`${styles.tabNavCtyScroll}`}>*/}
        {/*  <View className={`${styles.tabNavCtyList}`}>*/}
        {/*    {tabNav.list.map(cty => {*/}
        {/*      return (<View key={cty.id} className={classNames(`${styles.tabNavCtyItem}`, {[`${styles.tabNavCtyActive}`]: tabKey === cty.id})} onClick={this.onSwitchTab.bind(this, cty.id)}>*/}
        {/*        {cty.img ? (*/}
        {/*          <Image src={cty.img} mode='heightFix' className={`${styles.tabNavCtyImg}`}/>*/}
        {/*        ) : (*/}
        {/*          <Text className={`${styles.tabNavCtyText}`}>{cty.name}</Text>*/}
        {/*        )}*/}
        {/*      </View>)*/}
        {/*    })}*/}
        {/*  </View>*/}
        {/*</ScrollView>*/}
        {/*<View className={`${styles.tabNavRight}`} onClick={() => toSearchPage()}>全部</View>*/}
      </View>}

      <View className={`${styles.indexCustom}`} style={{ display: tabKey === defTabKey ? 'block' : 'none' }}>
        <View className={`${styles.indexCustomBg}`} style={{ paddingBottom: `${pxTransform(CAROUSEL_HEIGHT)}`, backgroundImage: `url(${pageConfig.bgImg})` }} />
        {customList.map((item, k) => {
          const { marginTop = 0, pageMargin = 0 } = item
          return (<View key={k}>
            {
              {
                'carousel': <CarouselTwo {...item} />,         // 轮播图
                'navGroup': <NavGroupTwo {...item} />,         // 导航组
                'newPeopleExclusive': <GoodsEight {...item} />,// 新人专享
                'fightGroups': <GoodsNine {...item} />,        // 拼团商品
                'newsService': <NewsOne {...item} />,          // 新闻播报
                'gridImg': <GridImg {...item} />,              // 栅格图片

                //  工具组件
                'blankSpace': <BlankSpace {...item} />,        // 新闻播报
                'auxiliaryLine': <AuxiliaryLine {...item} />,  // 栅格图片
                'goodsCategories': <GoodsCategories {...item} scroll={scroll} addNode={[this.navId]} />,  // 商品分类
                'activityTheme': <ActivityTheme {...item} />,  // 活动专区
                'promotion': <Promotion {...item} />,  // 营销板块
              }[item.key]
            }

            {/* 商品列表模板1 */}
            {item.key === 'seckill' && <View className={`${styles.goodsWrap} ${styles.goodsWrapOne}`} style={{ marginTop: `${pxTransform(marginTop)}` }}>
              {item.title && <View className={`${styles.goodsWrapHead} d-f a-i-b j-c-b`} style={{ padding: `0 ${pxTransform(pageMargin)}` }}>
                <View className={`${styles.goodsWrapTitle}`}>{item.title}</View>
                <View className={`${styles.goodsWrapMore} d-f a-i-c`} onClick={() => toAnyPage(item.moreUrl)}>
                  {item.moreName}
                  <View className='bnn-icon'>&#xe866;</View>
                </View>
              </View>}
              <View className={`${styles.goodsWrapBody}`}>
                <GoodsTen {...item} marginTop={pageMargin} />
              </View>
            </View>}

            {/* 商品列表模板1 */}
            {item.key === 'goodsList' && [2, 3, 4, 5, 6, 7].indexOf(Number(item.showMod)) >= 0 && <View className={`${styles.goodsWrap} ${styles.goodsWrapOne}`} style={{ marginTop: pxTransform(marginTop) }}>
              {item.title && <View className={`${styles.goodsWrapHead} d-f a-i-b j-c-b`} style={{ padding: `0 ${pxTransform(pageMargin)}` }}>
                <View className={`${styles.goodsWrapTitle}`}>{item.title}</View>
                <View className={`${styles.goodsWrapMore} d-f a-i-c`} onClick={() => toAnyPage(item.moreUrl)}>
                  {item.moreName}
                  <View className='bnn-icon'>&#xe866;</View>
                </View>
              </View>}
              {item.coverImg && <View className={`d-f`} style={{ padding: `0 ${pxTransform(pageMargin)}`, marginTop: `${pxTransform(pageMargin)}` }}>
                <Image mode="widthFix" src={item.coverImg} style={{ width: '100%' }} onClick={() => toAnyPage(item.coverUrl)} />
              </View>}
              <View className={`${styles.goodsWrapBody}`}>
                {
                  {
                    2: <GoodsTwo {...item} marginTop={pageMargin} />,
                    3: <GoodsThree {...item} marginTop={pageMargin} />,
                    4: <GoodsFour {...item} />,
                    5: <GoodsFive {...item} />,
                    6: <GoodsSix {...item} marginTop={pageMargin} />,
                    7: <GoodsSeven {...item} marginTop={pageMargin} />,
                  }[item.showMod]
                }
              </View>
            </View>}

            {/* 商品列表模板2 */}
            {item.key === 'goodsList' && [1].indexOf(Number(item.showMod)) >= 0 && <View className={`${styles.goodsWrap} ${styles.goodsWrapTwo}`} style={{ marginTop: pxTransform(marginTop) }}>
              {item.coverImg && <Image mode="widthFix" src={item.coverImg} style={{ width: '100%' }} onClick={() => toAnyPage(item.coverUrl)} />}
              <View className={`${styles.goodsWrapBox}`} style={{ margin: `${pxTransform(item.imgMarginTop)} ${pxTransform(item.pageMargin)} 0 ${pxTransform(item.pageMargin)}` }}>
                {item.title && <View className={`${styles.goodsWrapHead} d-f a-i-b j-c-b`}>
                  <View className={`${styles.goodsWrapTitle}`}>{item.title}</View>
                  <View className={`${styles.goodsWrapMore} d-f a-i-c`} onClick={() => toAnyPage(item.moreUrl)}>
                    {item.moreName}
                    <View className='bnn-icon'>&#xe866;</View>
                  </View>
                </View>}
                <View className={`${styles.goodsWrapBody}`}>
                  {/* 商品列表 */}
                  {item.showMod === 1 && <GoodsOne {...item} />}
                </View>
              </View>
            </View>}
          </View>)
        })}
        <Version />
      </View>
      <View style={{ display: tabKey !== defTabKey ? 'block' : 'none' }}>
        <GoodsTwo id={`goods-list`} list={goodsList} pageMargin={30} marginTop={30} />
        <LoadMore status={loadStatus} />
        {loadStatus === 'noMore' && <Version />}
      </View>

      <ActivityGoods isOpened={showActivity} info={activityInfo} onClose={this.closeActivity.bind(this)} />
      {/*<ActivityCoupon isOpened={showActivity} info={activityInfo} onClose={this.closeActivity.bind(this)}/>*/}

      {/*<BuyRecord top={pageConfig.showTabNav && tabNav ? 72 : 0}/>*/}

      <View style={{ height: `${TAB_BAR_HEIGHT}px` }} />
      <TabBar />
    </View>)
  }
}
